package com.dlnaplayer;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.jupnp.UpnpService;
import org.jupnp.UpnpServiceImpl;
import org.jupnp.controlpoint.ActionCallback;
import org.jupnp.controlpoint.ControlPoint;
import org.jupnp.model.action.ActionInvocation;
import org.jupnp.model.message.UpnpResponse;
import org.jupnp.model.meta.Device;
import org.jupnp.model.meta.LocalDevice;
import org.jupnp.model.meta.RemoteDevice;
import org.jupnp.model.meta.Service;
import org.jupnp.model.types.DeviceType;
import org.jupnp.model.types.ServiceType;
import org.jupnp.model.types.UDADeviceType;
import org.jupnp.model.types.UDAServiceType;
import org.jupnp.model.types.UnsignedIntegerFourBytes;
import org.jupnp.model.types.UnsignedIntegerTwoBytes;
import org.jupnp.registry.DefaultRegistryListener;
import org.jupnp.registry.Registry;
import org.jupnp.registry.RegistryListener;
import org.jupnp.support.avtransport.callback.GetPositionInfo;
import org.jupnp.support.avtransport.callback.GetTransportInfo;
import org.jupnp.support.avtransport.callback.Pause;
import org.jupnp.support.avtransport.callback.Play;
import org.jupnp.support.avtransport.callback.Seek;
import org.jupnp.support.avtransport.callback.SetAVTransportURI;
import org.jupnp.support.avtransport.callback.Stop;
import org.jupnp.support.model.DIDLContent;
import org.jupnp.support.model.DIDLObject;
import org.jupnp.support.model.PositionInfo;
import org.jupnp.support.model.Res;
import org.jupnp.support.model.TransportInfo;
import org.jupnp.support.model.TransportState;
import org.jupnp.support.model.item.VideoItem;
import org.jupnp.support.renderingcontrol.callback.GetMute;
import org.jupnp.support.renderingcontrol.callback.GetVolume;
import org.jupnp.support.renderingcontrol.callback.SetMute;
import org.jupnp.support.renderingcontrol.callback.SetVolume;
import org.jupnp.android.AndroidUpnpServiceConfiguration;
import org.jupnp.android.AndroidNetworkAddressFactory;
import org.jupnp.android.AndroidRouter;
import org.jupnp.binding.xml.DeviceDescriptorBinder;
import org.jupnp.binding.xml.ServiceDescriptorBinder;
import org.jupnp.binding.xml.UDA10DeviceDescriptorBinderImpl;
import org.jupnp.binding.xml.UDA10ServiceDescriptorBinderImpl;
import org.jupnp.model.meta.RemoteDeviceIdentity;
import org.jupnp.transport.impl.DatagramIOConfigurationImpl;
import org.jupnp.transport.impl.DatagramIOImpl;
import org.jupnp.transport.impl.MulticastReceiverConfigurationImpl;
import org.jupnp.transport.impl.MulticastReceiverImpl;
import org.jupnp.transport.impl.NetworkAddressFactoryImpl;
import org.jupnp.transport.impl.SOAPActionProcessorImpl;
import org.jupnp.transport.spi.DatagramIO;
import org.jupnp.transport.spi.DatagramProcessor;
import org.jupnp.transport.spi.GENAEventProcessor;
import org.jupnp.transport.spi.MulticastReceiver;
import org.jupnp.transport.spi.NetworkAddressFactory;
import org.jupnp.transport.spi.SOAPActionProcessor;
import org.jupnp.transport.spi.StreamClient;
import org.jupnp.transport.spi.StreamServer;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;

/**
 * DLNA服务管理器 - 使用jupnp库实现
 */
public abstract class DlnaServiceManager {
    private static final String TAG = "DlnaServiceManager";
    
    // 设备类型
    private static final DeviceType DEVICE_TYPE = new UDADeviceType("MediaRenderer", 1);
    
    // 服务类型
    private static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport", 1);
    private static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl", 1);
    
    // 实例ID
    private static final String INSTANCE_ID = "0";
    
    // 上下文
    private final Context context;
    
    // UPNP服务
    private UpnpService upnpService;
    
    // WiFi锁
    private WifiManager.MulticastLock multicastLock;
    
    // 设备列表
    private final Map<String, RemoteDevice> deviceMap = new ConcurrentHashMap<>();
    
    // 注册监听器
    private final RegistryListener registryListener = new DeviceRegistryListener();
    
    // 主线程Handler
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    // 线程池，用于执行异步任务
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    
    // 操作超时时间（毫秒）
    private static final long OPERATION_TIMEOUT = 8000; // 8秒
    
    // 最大重试次数
    private static final int MAX_RETRY_COUNT = 3;

    // 其他媒体渲染设备类型
    private static final DeviceType[] COMPATIBLE_DEVICE_TYPES = {
        new UDADeviceType("MediaRenderer", 1),  // 标准DLNA媒体渲染设备
        new UDADeviceType("AVTransport", 1),    // 一些设备可能使用这个类型
        new UDADeviceType("MediaServer", 1),    // 一些设备可能同时支持渲染和服务
        new UDADeviceType("Basic", 1),          // 基础设备，某些简单DLNA设备
    };
    
    // 是否自动重新搜索
    private boolean autoResearch = true;
    
    // 自动重新搜索间隔（毫秒）
    private static final long AUTO_RESEARCH_INTERVAL = 30000; // 30秒
    
    // 自动重新搜索Runnable
    private final Runnable researchRunnable = new Runnable() {
        @Override
        public void run() {
            if (autoResearch) {
                search();
                mainHandler.postDelayed(this, AUTO_RESEARCH_INTERVAL);
            }
        }
    };
    
    /**
     * Android专用jupnp配置
     */
    private static class AndroidJUPnPConfiguration extends AndroidUpnpServiceConfiguration {
        public AndroidJUPnPConfiguration() {
            // 使用默认构造函数，不需要调用super
        }
        
        @Override
        public NetworkAddressFactory createNetworkAddressFactory() {
            return new AndroidNetworkAddressFactory(
                0, // 使用默认端口0，让系统自动分配
                NetworkAddressFactoryImpl.DEFAULT_MULTICAST_RESPONSE_LISTEN_PORT
            );
        }
        
        @Override
        public SOAPActionProcessor getSoapActionProcessor() {
            return new SOAPActionProcessorImpl();
        }
        
        @Override
        public GENAEventProcessor getGenaEventProcessor() {
            return super.getGenaEventProcessor();
        }
        
        @Override
        public DatagramProcessor getDatagramProcessor() {
            return super.getDatagramProcessor();
        }
        
        @Override
        public StreamClient createStreamClient() {
            return super.createStreamClient();
        }
        
        @Override
        public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory) {
            return super.createStreamServer(networkAddressFactory);
        }
        
        @Override
        public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory) {
            return new MulticastReceiverImpl(
                new MulticastReceiverConfigurationImpl(
                    networkAddressFactory.getMulticastGroup(),
                    networkAddressFactory.getMulticastPort()
                )
            );
        }
        
        @Override
        public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory) {
            return new DatagramIOImpl(new DatagramIOConfigurationImpl());
        }
        
        @Override
        public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10() {
            return new UDA10DeviceDescriptorBinderImpl();
        }
        
        @Override
        public ServiceDescriptorBinder getServiceDescriptorBinderUDA10() {
            return new UDA10ServiceDescriptorBinderImpl();
        }
    }
    
    /**
     * 构造函数
     * @param context 上下文
     */
    public DlnaServiceManager(Context context) {
        this.context = context;
        
        try {
            // 获取WiFi锁
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager == null) {
                throw new IllegalStateException("无法获取WifiManager服务");
            }
            
            multicastLock = wifiManager.createMulticastLock(TAG);
            multicastLock.setReferenceCounted(true);
            
            // 创建UPNP服务 - 使用Android专用配置
            try {
                upnpService = new UpnpServiceImpl(new AndroidJUPnPConfiguration());
                
                // 添加注册监听器
                upnpService.getRegistry().addListener(registryListener);
                
                Log.d(TAG, "DLNA服务管理器初始化成功");
            } catch (Exception e) {
                Log.e(TAG, "创建UPNP服务失败: " + e.getMessage(), e);
                throw new IllegalStateException("创建UPNP服务失败", e);
            }
        } catch (Exception e) {
            Log.e(TAG, "DLNA服务管理器初始化失败: " + e.getMessage(), e);
            throw new IllegalStateException("DLNA服务管理器初始化失败", e);
        }
    }
    
    /**
     * 析构函数，确保资源被正确释放
     */
    @Override
    protected void finalize() throws Throwable {
        try {
            // 确保资源被释放
            release();
        } finally {
            super.finalize();
        }
    }
    
    /**
     * 设备添加回调（由子类实现）
     * @param device 设备信息
     */
    protected abstract void onDeviceAdded(Map<String, Object> device);
    
    /**
     * 设备移除回调（由子类实现）
     * @param device 设备信息
     */
    protected abstract void onDeviceRemoved(Map<String, Object> device);

    /**
     * 搜索设备
     */
    public void search() {
        // 获取WiFi锁
        if (!multicastLock.isHeld()) {
            multicastLock.acquire();
        }
        
        // 搜索设备
        upnpService.getControlPoint().search();
    }

    /**
     * 停止搜索设备
     */
    public void stopSearch() {
        // 释放WiFi锁
        if (multicastLock != null && multicastLock.isHeld()) {
            multicastLock.release();
        }
    }

    /**
     * 获取设备列表
     * @return 设备列表
     */
    public List<Map<String, Object>> getDevices() {
        // 添加同步锁，确保线程安全
        synchronized(deviceMap) {
            List<Map<String, Object>> devices = new ArrayList<>();
            
            for (Map.Entry<String, RemoteDevice> entry : deviceMap.entrySet()) {
                RemoteDevice device = entry.getValue();
                
                // 检查设备是否支持AVTransport服务
                if (device.findService(AV_TRANSPORT_SERVICE) == null) {
                    continue;
                }
                
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("id", entry.getKey());
                deviceInfo.put("name", device.getDetails().getFriendlyName());
                deviceInfo.put("ipAddress", device.getIdentity().getDescriptorURL().getHost());
                deviceInfo.put("model", device.getDetails().getModelDetails().getModelName());
                deviceInfo.put("manufacturer", device.getDetails().getManufacturerDetails().getManufacturer());
                
                devices.add(deviceInfo);
            }
            
            return devices;
        }
    }

    /**
     * 连接设备
     * @param deviceId 设备ID
     * @return 是否连接成功
     */
    public boolean connect(String deviceId) {
        return deviceMap.containsKey(deviceId);
    }

    /**
     * 断开设备连接
     * @param deviceId 设备ID
     * @return 是否断开成功
     */
    public boolean disconnect(String deviceId) {
        try {
            RemoteDevice device = deviceMap.get(deviceId);
            if (device == null) {
                // 设备不存在或已经断开，视为成功
                return true;
            }
            
            Service<?, ?> avTransportService = device.findService(AV_TRANSPORT_SERVICE);
            if (avTransportService != null) {
                try {
                    // 尝试停止当前播放
                    upnpService.getControlPoint().execute(new Stop(new UnsignedIntegerFourBytes(INSTANCE_ID), avTransportService) {
                        @Override
                        public void success(ActionInvocation invocation) {
                            Log.d(TAG, "Stop on disconnect success");
                        }
                        
                        @Override
                        public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                            Log.e(TAG, "Stop on disconnect failed: " + defaultMsg);
                        }
                    });
                } catch (Exception e) {
                    Log.e(TAG, "Error stopping playback on disconnect: " + e.getMessage());
                    // 继续断开过程，即使停止失败
                }
            }
            
            // 记录断开日志
            Log.d(TAG, "Device disconnected: " + device.getDetails().getFriendlyName());
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Disconnect error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 播放视频
     * @param deviceId 设备ID
     * @param url 视频URL
     * @param title 视频标题
     * @param subtitle 视频副标题
     * @param coverUrl 封面URL
     * @return 是否播放成功
     */
    public boolean play(String deviceId, String url, String title, String subtitle, String coverUrl) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            // 创建DIDL内容
            DIDLContent didlContent = new DIDLContent();
            
            // 创建视频项
            String id = UUID.randomUUID().toString();
            
            // jupnp的Res构造函数与Cling不同，先创建一个空Res
            Res res = new Res();
            res.setValue(url);
            res.setDuration("00:00:00");
            
            VideoItem videoItem = new VideoItem(id, "0", title != null ? title : "Video", "Unknown");
            videoItem.addResource(res);
            
            // 添加封面
            if (coverUrl != null) {
                try {
                    DIDLObject.Property<URI> albumArtURI = new DIDLObject.Property.UPNP.ALBUM_ART_URI(URI.create(coverUrl));
                    videoItem.addProperty(albumArtURI);
                } catch (Exception e) {
                    Log.e(TAG, "Error adding album art: " + e.getMessage());
                }
            }
            
            // 添加视频项
            didlContent.addItem(videoItem);
            
            // 设置URI
            final String metadata = didlContent.toString();
            final ControlPoint controlPoint = upnpService.getControlPoint();
            
            // 设置传输URI
            controlPoint.execute(new SetAVTransportURI(new UnsignedIntegerFourBytes(INSTANCE_ID), service, url, metadata) {
                @Override
                public void success(ActionInvocation invocation) {
                    // 播放
                    controlPoint.execute(new Play(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                        @Override
                        public void success(ActionInvocation invocation) {
                            Log.d(TAG, "Play success");
                        }
                        
                        @Override
                        public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                            Log.e(TAG, "Play failed: " + defaultMsg);
                        }
                    });
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "SetAVTransportURI failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Play error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 暂停播放
     * @param deviceId 设备ID
     * @return 是否暂停成功
     */
    public boolean pause(String deviceId) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            upnpService.getControlPoint().execute(new Pause(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "Pause success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "Pause failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Pause error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 恢复播放
     * @param deviceId 设备ID
     * @return 是否恢复成功
     */
    public boolean resume(String deviceId) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            upnpService.getControlPoint().execute(new Play(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "Resume success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "Resume failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Resume error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 停止播放
     * @param deviceId 设备ID
     * @return 是否停止成功
     */
    public boolean stop(String deviceId) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            upnpService.getControlPoint().execute(new Stop(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "Stop success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "Stop failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Stop error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 跳转到指定位置
     * @param deviceId 设备ID
     * @param position 位置（毫秒）
     * @return 是否跳转成功
     */
    public boolean seekTo(String deviceId, long position) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            // 转换为时间格式 HH:MM:SS
            long seconds = position / 1000;
            long hours = seconds / 3600;
            long minutes = (seconds % 3600) / 60;
            long remainingSeconds = seconds % 60;
            
            String target = String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds);
            
            upnpService.getControlPoint().execute(new Seek(new UnsignedIntegerFourBytes(INSTANCE_ID), service, target) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "Seek success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "Seek failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Seek error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取播放状态
     * @param deviceId 设备ID
     * @return 播放状态
     */
    public Map<String, Object> getPlaybackStatus(String deviceId) {
        final Map<String, Object> status = new HashMap<>();
        status.put("isPlaying", false);
        status.put("position", 0L);
        status.put("duration", 0L);
        status.put("isBuffering", false);
        status.put("isCompleted", false);
        status.put("isError", false);
        
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            status.put("isError", true);
            status.put("errorMessage", "设备未找到");
            return status;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            status.put("isError", true);
            status.put("errorMessage", "设备不支持AVTransport服务");
            return status;
        }
        
        try {
            // 获取传输信息
            final GetTransportInfo getTransportInfo = new GetTransportInfo(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void received(ActionInvocation invocation, TransportInfo transportInfo) {
                    TransportState state = transportInfo.getCurrentTransportState();
                    status.put("isPlaying", state == TransportState.PLAYING);
                    status.put("isBuffering", state == TransportState.TRANSITIONING);
                    status.put("isCompleted", state == TransportState.STOPPED);
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    status.put("isError", true);
                    status.put("errorMessage", "获取传输信息失败: " + defaultMsg);
                }
            };
            
            // 获取位置信息
            final GetPositionInfo getPositionInfo = new GetPositionInfo(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void received(ActionInvocation invocation, PositionInfo positionInfo) {
                    status.put("position", positionInfo.getTrackElapsedSeconds() * 1000L);
                    status.put("duration", positionInfo.getTrackDurationSeconds() * 1000L);
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    status.put("isError", true);
                    status.put("errorMessage", "获取位置信息失败: " + defaultMsg);
                }
            };
            
            // 执行操作
            upnpService.getControlPoint().execute(getTransportInfo);
            upnpService.getControlPoint().execute(getPositionInfo);
            
            return status;
        } catch (Exception e) {
            status.put("isError", true);
            status.put("errorMessage", "获取播放状态失败: " + e.getMessage());
            return status;
        }
    }

    /**
     * 设置音量
     * @param deviceId 设备ID
     * @param volume 音量（0-100）
     * @return 是否设置成功
     */
    public boolean setVolume(String deviceId, int volume) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(RENDERING_CONTROL_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            upnpService.getControlPoint().execute(new SetVolume(new UnsignedIntegerFourBytes(INSTANCE_ID), service, volume) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "SetVolume success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "SetVolume failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "SetVolume error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取音量
     * @param deviceId 设备ID
     * @return 音量（0-100）
     */
    public int getVolume(String deviceId) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return 0;
        }
        
        Service<?, ?> service = device.findService(RENDERING_CONTROL_SERVICE);
        if (service == null) {
            return 0;
        }
        
        try {
            final int[] volume = {0};
            
            GetVolume getVolume = new GetVolume(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void received(ActionInvocation invocation, int currentVolume) {
                    volume[0] = currentVolume;
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "GetVolume failed: " + defaultMsg);
                }
            };
            
            upnpService.getControlPoint().execute(getVolume);
            
            return volume[0];
        } catch (Exception e) {
            Log.e(TAG, "GetVolume error: " + e.getMessage());
            return 0;
        }
    }

    /**
     * 设置静音
     * @param deviceId 设备ID
     * @param mute 是否静音
     * @return 是否设置成功
     */
    public boolean setMute(String deviceId, boolean mute) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(RENDERING_CONTROL_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            upnpService.getControlPoint().execute(new SetMute(new UnsignedIntegerFourBytes(INSTANCE_ID), service, mute) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "SetMute success");
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "SetMute failed: " + defaultMsg);
                }
            });
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "SetMute error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取静音状态
     * @param deviceId 设备ID
     * @return 是否静音
     */
    public boolean getMute(String deviceId) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            return false;
        }
        
        Service<?, ?> service = device.findService(RENDERING_CONTROL_SERVICE);
        if (service == null) {
            return false;
        }
        
        try {
            final boolean[] mute = {false};
            
            GetMute getMute = new GetMute(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void received(ActionInvocation invocation, boolean currentMute) {
                    mute[0] = currentMute;
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "GetMute failed: " + defaultMsg);
                }
            };
            
            upnpService.getControlPoint().execute(getMute);
            
            return mute[0];
        } catch (Exception e) {
            Log.e(TAG, "GetMute error: " + e.getMessage());
            return false;
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        // 停止搜索
        stopSearch();
        
        // 移除注册监听器
        if (upnpService != null) {
            upnpService.getRegistry().removeListener(registryListener);
            upnpService.shutdown();
            upnpService = null;
        }
        
        // 关闭线程池
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                // 等待任务完成
                if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
        
        // 清空设备列表
        deviceMap.clear();
    }

    /**
     * 带超时的设备搜索
     * @param timeoutMs 超时时间（毫秒）
     * @return 是否成功启动搜索
     */
    public boolean searchWithTimeout(long timeoutMs) {
        try {
            // 获取WiFi锁
            if (!multicastLock.isHeld()) {
                multicastLock.acquire();
            }
            
            // 在后台线程执行搜索，避免阻塞主线程
            Future<?> searchTask = executorService.submit(() -> {
                try {
                    upnpService.getControlPoint().search();
                } catch (Exception e) {
                    Log.e(TAG, "Search error: " + e.getMessage());
                }
            });
            
            // 设置超时
            try {
                searchTask.get(timeoutMs, TimeUnit.MILLISECONDS);
                return true;
            } catch (TimeoutException e) {
                Log.w(TAG, "Search operation timed out");
                return false;
            } catch (Exception e) {
                Log.e(TAG, "Search operation error: " + e.getMessage());
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error starting search: " + e.getMessage());
            return false;
        }
    }

    /**
     * 设置是否自动重新搜索
     * @param autoResearch 是否自动重新搜索
     */
    public void setAutoResearch(boolean autoResearch) {
        this.autoResearch = autoResearch;
        
        // 停止当前的自动重新搜索计划
        mainHandler.removeCallbacks(researchRunnable);
        
        // 如果启用，开始自动重新搜索
        if (autoResearch) {
            mainHandler.postDelayed(researchRunnable, AUTO_RESEARCH_INTERVAL);
        }
    }
    
    /**
     * 根据设备类型检查设备是否兼容
     * @param device 设备
     * @return 是否兼容
     */
    private boolean isCompatibleDevice(RemoteDevice device) {
        // 检查设备类型
        DeviceType deviceType = device.getType();
        
        // 首先检查主要类型
        if (DEVICE_TYPE.equals(deviceType)) {
            return true;
        }
        
        // 检查兼容类型
        for (DeviceType compatibleType : COMPATIBLE_DEVICE_TYPES) {
            if (compatibleType.equals(deviceType)) {
                return true;
            }
        }
        
        // 如果设备类型不匹配，还可以检查是否支持AVTransport服务
        return device.findService(AV_TRANSPORT_SERVICE) != null;
    }
    
    /**
     * 清除设备列表
     */
    public void clearDevices() {
        synchronized(deviceMap) {
            deviceMap.clear();
        }
    }
    
    /**
     * 强制搜索设备
     * 先清除现有设备列表，然后开始新搜索
     */
    public void forceSearch() {
        clearDevices();
        search();
    }

    /**
     * 设备注册监听器
     */
    private class DeviceRegistryListener extends DefaultRegistryListener {
        @Override
        public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
            // 检查设备类型是否兼容
            if (isCompatibleDevice(device)) {
                String deviceId = device.getIdentity().getUdn().getIdentifierString();
                deviceMap.put(deviceId, device);
                
                Log.d(TAG, "Remote device added: " + device.getDetails().getFriendlyName() + 
                      " (Type: " + device.getType() + ")");
                
                // 创建设备信息
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("id", deviceId);
                deviceInfo.put("name", device.getDetails().getFriendlyName());
                deviceInfo.put("ipAddress", device.getIdentity().getDescriptorURL().getHost());
                deviceInfo.put("model", device.getDetails().getModelDetails().getModelName());
                deviceInfo.put("manufacturer", device.getDetails().getManufacturerDetails().getManufacturer());
                deviceInfo.put("type", device.getType().toString());
                
                // 调用回调
                onDeviceAdded(deviceInfo);
            } else {
                Log.d(TAG, "忽略不兼容设备: " + device.getDetails().getFriendlyName() + 
                      " (Type: " + device.getType() + ")");
            }
        }

        @Override
        public void remoteDeviceRemoved(Registry registry, RemoteDevice device) {
            String deviceId = device.getIdentity().getUdn().getIdentifierString();
            
            if (deviceMap.containsKey(deviceId)) {
                RemoteDevice removedDevice = deviceMap.remove(deviceId);
                
                Log.d(TAG, "Remote device removed: " + device.getDetails().getFriendlyName());
                
                // 创建设备信息
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("id", deviceId);
                deviceInfo.put("name", removedDevice.getDetails().getFriendlyName());
                deviceInfo.put("ipAddress", removedDevice.getIdentity().getDescriptorURL().getHost());
                deviceInfo.put("model", removedDevice.getDetails().getModelDetails().getModelName());
                deviceInfo.put("manufacturer", removedDevice.getDetails().getManufacturerDetails().getManufacturer());
                
                // 调用回调
                onDeviceRemoved(deviceInfo);
            }
        }

        @Override
        public void localDeviceAdded(Registry registry, LocalDevice device) {
            Log.d(TAG, "Local device added: " + device.getDetails().getFriendlyName());
        }

        @Override
        public void localDeviceRemoved(Registry registry, LocalDevice device) {
            Log.d(TAG, "Local device removed: " + device.getDetails().getFriendlyName());
        }
    }

    /**
     * 带重试功能的播放方法
     * @param deviceId 设备ID
     * @param url 视频URL
     * @param title 视频标题
     * @param subtitle 视频副标题
     * @param coverUrl 封面URL
     * @return 是否播放成功
     */
    public boolean playWithRetry(String deviceId, String url, String title, String subtitle, String coverUrl) {
        int retryCount = 0;
        boolean success = false;
        Exception lastException = null;
        
        while (retryCount < MAX_RETRY_COUNT && !success) {
            try {
                if (retryCount > 0) {
                    Log.i(TAG, "重试播放操作，尝试次数: " + (retryCount + 1));
                    // 每次重试前等待一段时间
                    Thread.sleep(1000 * retryCount);
                }
                
                success = play(deviceId, url, title, subtitle, coverUrl);
                
                if (!success && retryCount < MAX_RETRY_COUNT - 1) {
                    Log.w(TAG, "播放失败，准备重试...");
                }
            } catch (Exception e) {
                lastException = e;
                Log.e(TAG, "播放出错: " + e.getMessage());
            }
            
            retryCount++;
        }
        
        if (!success && lastException != null) {
            Log.e(TAG, "播放操作在" + MAX_RETRY_COUNT + "次尝试后失败: " + lastException.getMessage());
        }
        
        return success;
    }
    
    /**
     * 带重试功能的AVTransport操作
     * @param deviceId 设备ID
     * @param operation 操作名称，用于日志
     * @param action 要执行的操作
     * @return 是否成功
     */
    private boolean executeWithRetry(String deviceId, String operation, TransportAction action) {
        RemoteDevice device = deviceMap.get(deviceId);
        if (device == null) {
            Log.e(TAG, operation + " 失败: 设备未找到");
            return false;
        }
        
        Service<?, ?> service = device.findService(AV_TRANSPORT_SERVICE);
        if (service == null) {
            Log.e(TAG, operation + " 失败: 设备不支持AVTransport服务");
            return false;
        }
        
        int retryCount = 0;
        boolean success = false;
        Exception lastException = null;
        
        while (retryCount < MAX_RETRY_COUNT && !success) {
            try {
                if (retryCount > 0) {
                    Log.i(TAG, "重试" + operation + "操作，尝试次数: " + (retryCount + 1));
                    // 每次重试前等待一段时间
                    Thread.sleep(1000 * retryCount);
                }
                
                success = action.execute(service);
                
                if (!success && retryCount < MAX_RETRY_COUNT - 1) {
                    Log.w(TAG, operation + "失败，准备重试...");
                }
            } catch (Exception e) {
                lastException = e;
                Log.e(TAG, operation + "出错: " + e.getMessage());
            }
            
            retryCount++;
        }
        
        if (!success && lastException != null) {
            Log.e(TAG, operation + "操作在" + MAX_RETRY_COUNT + "次尝试后失败: " + lastException.getMessage());
        }
        
        return success;
    }
    
    /**
     * 功能性接口，用于封装传输操作
     */
    private interface TransportAction {
        boolean execute(Service<?, ?> service) throws Exception;
    }
    
    /**
     * 带重试功能的暂停操作
     */
    public boolean pauseWithRetry(String deviceId) {
        return executeWithRetry(deviceId, "暂停", service -> {
            final boolean[] result = {false};
            
            upnpService.getControlPoint().execute(new Pause(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "暂停操作成功");
                    result[0] = true;
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "暂停操作失败: " + defaultMsg);
                }
            });
            
            return result[0];
        });
    }
    
    /**
     * 带重试功能的恢复播放操作
     */
    public boolean resumeWithRetry(String deviceId) {
        return executeWithRetry(deviceId, "恢复播放", service -> {
            final boolean[] result = {false};
            
            upnpService.getControlPoint().execute(new Play(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "恢复播放操作成功");
                    result[0] = true;
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "恢复播放操作失败: " + defaultMsg);
                }
            });
            
            return result[0];
        });
    }
    
    /**
     * 带重试功能的停止操作
     */
    public boolean stopWithRetry(String deviceId) {
        return executeWithRetry(deviceId, "停止", service -> {
            final boolean[] result = {false};
            
            upnpService.getControlPoint().execute(new Stop(new UnsignedIntegerFourBytes(INSTANCE_ID), service) {
                @Override
                public void success(ActionInvocation invocation) {
                    Log.d(TAG, "停止操作成功");
                    result[0] = true;
                }
                
                @Override
                public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
                    Log.e(TAG, "停止操作失败: " + defaultMsg);
                }
            });
            
            return result[0];
        });
    }
} 